package com.controller;

import com.request.FileCreateRequest;
import com.request.FileDeleteRequest;
import com.request.FileRenameRequest;
import com.request.FileSaveRequest;
import com.service.FileManageService;
import com.utils.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * @author rkc
 * @date 2022/8/20 20:40
 */
@RestController
@RequestMapping("/api/v1/file")
public class FileManageController {

    @Autowired
    private FileManageService fileManageService;

    /**
     * 保存文件
     * @param fileSaveRequest
     * @return
     */
    @PostMapping("save")
    public JsonData save(@RequestBody FileSaveRequest fileSaveRequest) {
        return fileManageService.saveFile(fileSaveRequest);
    }

    /**
     * 重命名
     * @param fileRenameRequest
     * @return
     */
    @PostMapping("rename")
    public JsonData rename(@RequestBody FileRenameRequest fileRenameRequest) {
        return fileManageService.rename(fileRenameRequest);
    }

    /**
     * 树状展示目录、文件
     * @param name
     * @return
     */
    @GetMapping("show_directory/{name}")
    public JsonData showDirectory(@PathVariable("name") String name) {
        return fileManageService.showDirectory(name);
    }

    /**
     * 创建文件
     * @param fileCreateRequest
     * @return
     */
    @PostMapping("create_file")
    public JsonData createFile(@RequestBody FileCreateRequest fileCreateRequest) {
        return fileManageService.createFile(fileCreateRequest);
    }

    /**
     * 创建目录
     * @param fileCreateRequest
     * @return
     */
    @PostMapping("create_directory")
    public JsonData createDirectory(@RequestBody FileCreateRequest fileCreateRequest) {
        return fileManageService.createDirectory(fileCreateRequest);
    }

    /**
     * 删除所有文件/目录
     * @param fileDeleteRequest
     * @return
     */
    @PostMapping("delete_all")
    public JsonData deleteAll(@RequestBody FileDeleteRequest fileDeleteRequest) {
        return fileManageService.deleteAll(fileDeleteRequest);
    }

    /**
     * 读取指定文件内容
     * @param path
     * @param request
     * @return
     */
    @GetMapping("get_file/{path}/**")
    public JsonData getFile(@PathVariable("path") String path, HttpServletRequest request) {
        //得到带有参数的uri和原uri
        String p = request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE).toString(), q = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE).toString();
        String arguments = new AntPathMatcher().extractPathWithinPattern(q, p);
        String moduleName;
        if (!arguments.isEmpty()) {
            moduleName = path + "/" + arguments;
        } else {
            moduleName = path;
        }
        return fileManageService.getFile(moduleName);
    }
}
